package gupao.concurrency.datasync.tbapi;

import gupao.concurrency.utils.JsonUtils;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

@Component
public class TciWordDataApi {
    private final static PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    static{
        connectionManager.setDefaultMaxPerRoute(300);
        connectionManager.setMaxTotal(1500);
    }
    private final static HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder.create()
                    .setRedirectStrategy(new DefaultRedirectStrategy(){
                        @Override
                        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
                            return false;
                        }
                    })
                    .setConnectionManager(connectionManager)
                    .build());
    private final static RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

    private final static String TCI_WORD_SINGLE_API_PREFIX = "http://localhost:10001/tciword/rpt/single/";

    public Resp syncTciWordReport(String word){
        if(StringUtils.hasText(word)){
            ResponseEntity<String> respEntity = restTemplate.getForEntity(TCI_WORD_SINGLE_API_PREFIX+word, String.class);
            if(respEntity.getStatusCodeValue() == 200){
                String body = respEntity.getBody();
                return JsonUtils.toResp(body);
            }
            return Resp.builder().code("0").msg("http status error").build();
        }
        return null;
    }
}
